<template>
  <div v-show="showAudioRecordModal" class="c-flex-column c-justify-end" :class="isSimpleQue?'modalSimpleQue':'modal'">
    <div class="masker c-flex-grow1" v-if="!isSimpleQue" @click="closeAudioRecordModal"></div>
    <div class="modal-content">
      <div class="iconfont c-fs32 c-fc-white c-pa c-p-r32 c-p-t32 c-fc-gray" @click="closeAudioRecordModal">&#xe84e;</div>
      <!-- 未开始 -->
      <div v-if="recordStatus == 'START'" class="c-hh380 c-bg-white c-flex-column c-flex-center">
        <div class="c-fs24 c-pb30 c-fc-gray">点击开始录音</div>
        <div class="c-flex-row c-flex-center theme-bg c-ww140 c-brp50 c-hh140" @click="clickStartRecord">
          <i class="iconfont c-fs60 c-fc-white">&#xe741;</i>
        </div>
        <div class="c-fs24 c-pt24">
          <span class="theme-fc">{{timeToMS}}</span>
        </div>
        <div v-if="enableLongAudio==0&&isclock&&!$isStore()" class="c-fs24 c-textAlign-c c-mt20">如需录制更长的语音，请前往<span class="c-p theme-fc">小程序打卡
          <div class="open-tag-wrap" v-if="isSupport">
            <wx-open-launch-weapp
              class="launch-btn"
              :appid="`${appid}`"
              :username="username"
              :path="`${path}?${wxappQuery}`"
              @error="handleErrorFn"
              @launch="handleLaunch"
            >
              <script type="text/wxtag-template">
                <!-- 这里是为了撑开元素，让其可以被点击，不添加template会报错，添加了template不添加内容也会报错 -->
                <div style="padding: 10000px">
                </div>
              </script>
            </wx-open-launch-weapp>
          </div>
          <div v-else class="open-tag-wrap" @click="clickGoWxApp"></div>
        </span>
        </div>
      </div>
      <!-- 正在录 -->
      <div v-else-if="recordStatus == 'RECORDING'" class="c-hh380 c-bg-white c-flex-column c-flex-center">
        <!-- <img @click="clickStopRecord" class="c-ww100 c-hh100" src="@/assets/i/wap/course/audio_record.gif" alt="" /> -->
        <div class="c-fs24 c-pb30 c-fc-gray">点击结束录音</div>
        <div class="c-flex-row c-flex-center theme-bg c-ww140 c-brp50 c-hh140" @click="clickStopRecord">
          <i class="iconfont c-fs60 c-fc-white">&#xea6f;</i>
        </div>
        <div class="c-fs24 c-pt24">
          <!-- <span>录音中，已录制</span> -->
          <span class="theme-fc">{{timeToMS}}</span>
        </div>
        <!-- <div v-if="enableLongAudio==1" class="c-fs24 c-textAlign-c c-mt20">如需录制更长的语音，请前往<span class="c-p theme-fc">小程序打卡
        <div v-if="enableLongAudio==0&&isclock" class="c-fs24 c-textAlign-c c-mt20">如需录制更长的语音，请前往<span class="c-p theme-fc">小程序打卡
          <div class="open-tag-wrap" v-if="isSupport">
            <wx-open-launch-weapp
              class="launch-btn"
              :appid="`${appid}`"
              :username="username"
              :path="`${path}?${wxappQuery}`"
              @error="handleErrorFn"
              @launch="handleLaunch"
            >
              <script type="text/wxtag-template">
                <div style="padding: 10000px">
                </div>
              </script>
            </wx-open-launch-weapp>
          </div>
          <div v-else class="open-tag-wrap" @click="clickGoWxApp"></div>
        </span>
        </div> -->
      </div>
      <!-- 已完成 -->
      <div v-else class="c-hh380 c-bg-white c-flex-column c-flex-center">
        <div class="c-flex-row c-w100">
          <div class="c-flex-grow1 c-w0">
            <div @click="clickRecordAgain" class="c-ww80 c-textAlign-c c-center c-hh80 c-lh80 iconfont c-mb20 c-mt124 c-fs40 c-fc-white theme-bg c-brp50">&#xe7b8;</div>
            <div class="c-fs24 c-fc-gray c-textAlign-c">重录</div>
          </div>
          <div class="c-flex-grow1 c-w0">
            <div class="c-fs24 c-pb30">
              <span>本次共录制</span>
              <span class="theme-fc">{{timeToMS}}</span>
            </div>
            <div @click="syncUploadAudio(1)" class="c-ww140 c-textAlign-c c-center c-hh140 c-lh140 iconfont c-mb20 c-fs60 c-fc-white theme-bg c-brp50">&#xe618;</div>
            <div class="c-fs24 c-fc-gray c-textAlign-c">发送</div>
          </div>
          <div class="c-flex-grow1 c-w0">
            <div v-if="isWeiXin">
              <div @click="clickTryListen(1)" class="c-ww80 c-textAlign-c c-center c-hh80 c-lh80 iconfont c-mb20 c-mt124 c-fs40 c-fc-white theme-bg c-brp50">&#xe740;</div>
              <div class="c-fs24 c-fc-gray c-textAlign-c">{{isPlayTest ? '试听中':'试听'}}</div>
            </div>
          </div>
          <!-- <div class="c-flex-grow1 c-w0">
            <div @click="clickTryListen(1)" class="c-fs24 theme-fc c-flex-grow1 c-w0 c-textAlign-c c-pv20">{{isWeiXin ? (isPlayTest ? '试听中':'试听') : ''}}</div>
          </div> -->
        </div>
        <div v-if="enableLongAudio==0&&isclock&&!$isStore()" class="c-fs24 c-textAlign-c c-mt20">如需录制更长的语音，请前往<span class="c-p theme-fc">小程序打卡
          <div class="open-tag-wrap" v-if="isSupport">
            <wx-open-launch-weapp
              class="launch-btn"
              :appid="`${appid}`"
              :username="username"
              :path="`${path}?${wxappQuery}`"
              @error="handleErrorFn"
              @launch="handleLaunch"
            >
              <script type="text/wxtag-template">
                <!-- 这里是为了撑开元素，让其可以被点击，不添加template会报错，添加了template不添加内容也会报错 -->
                <div style="padding: 10000px">
                </div>
              </script>
            </wx-open-launch-weapp>
          </div>
          <div v-else class="open-tag-wrap" @click="clickGoWxApp"></div>
        </span>
        </div>
      </div>

    </div>
  </div>
</template>

<script>
import { utilJs, wxUtilJs } from "@/utils/common.js";
import record from "@/utils/recorder.js";
let recordTimeCon; //录音计时控制器
let currentLocalId; //当前录音ID
export default {
  components: {},
  props: {
    showAudioRecordModal: {
      //绑定的输入框的值
      type: Boolean,
      default: false
    },
    clockInInfo:{
      type:Object,
      default: () => {}
    },
    enableLongAudio:{
      type:Number,
      default: 0
    },
    isclock: {
      //是否是打卡
      type: Boolean,
      default: false
    },
    isSimpleQue: {
      //绑定的输入框的值
      type: Boolean,
      default: false
    },
  },
  data() {
    return {
      recordStatus: "START",
      recordTime: 0,
      showRecordTime:0,
      isPlayTest: false, //是否试听播放
      isWeiXin: true,
      isPcWechat:false,
      isSupport:localStorage.getItem('isWxApp') != 1,
      qiniuInfo: {}, //录音完后的音频上传到七牛，这里是七牛的相关信息
      blob: "", //录音之后要上传七牛的音频文件
      mediaIds:[],
      localMedId:[], //本地微信录音id
      mediaIndex:0, //当前播放下标
      appid:'wxc99b13f1a0b51048',
      wxappQuery: "",
      path:'/pages/clockIn/homeWorker/index',
    };
  },
  created() {
    if (!utilJs.isWeiXin() || (utilJs.isWeiXin() && !utilJs.isMobileUserAgent())) {
      utilJs.getMethod(
        global.apiurl + "common/qiniu/uploadToken",
        (res) => {
          this.qiniuInfo.qiNiuToken = res;
        }
      );
    }
  },
  computed: {
    //日期转化成分秒
    timeToMS: function() {
      const ONE_MINUTE_TIMESTAMP = 60;
      const ONE_SECONDS_TIMESTAMP = 1;
      let timeTmp = this.showRecordTime
      let minuteNum = Math.floor(timeTmp / ONE_MINUTE_TIMESTAMP);
      let secondsNum = Math.floor((timeTmp - minuteNum * ONE_MINUTE_TIMESTAMP) / ONE_SECONDS_TIMESTAMP);
      if (minuteNum >= 0 && minuteNum < 10) {
        minuteNum = '0' + minuteNum;
      }
      if (secondsNum >= 0 && secondsNum < 10) {
        secondsNum = '0' + secondsNum;
      }
      return `${minuteNum}:${secondsNum}`;
    },
  },
  watch: {
    showAudioRecordModal(val) {
      this.isWeiXin = utilJs.isWeiXin();
      this.isPcWechat = utilJs.isWeiXin() && !utilJs.isMobileUserAgent();
      if (val) {
        if (this.isWeiXin && !this.isPcWechat) {
          wxUtilJs.stopRecord();
        } else {
          record.recClose();
        }
        currentLocalId = "";
        recordTimeCon && clearInterval(recordTimeCon);
        this.recordStatus = "START";
        this.recordTime = 0;
        this.showRecordTime = 0
        this.isPlayTest = false;
        this.mediaIndex = 0
        wxUtilJs.onVoicePlayEnd(() => {
          //监听微信语音播放结束事件
          this.isPlayTest = false;
        });
      } else {
        clearInterval(recordTimeCon);
        if (this.recordStatus == "RECORDING") {
          if (this.isWeiXin && !this.isPcWechat) {
            wxUtilJs.stopRecord();
          } else {
            record.recClose();
          }
        }
        this.stopListenAudio();
      }
      if (this.clockInInfo) {
        switch (this.clockInInfo.type) {
            case 1:
              //日历打卡,若当前日期不在开始日期和结束日期之间，则从开始日期进入，否则从当前日期进入
              let startTimeTamp = new Date(`${this.clockInInfo.startTime} ${this.clockInInfo.startHour}`.replace(/-/g, "/")).getTime();
              let endTimeTamp = new Date(`${this.clockInInfo.endTime} ${this.clockInInfo.endHour}`.replace(/-/g, "/")).getTime();
              let nowTimeTamp = new Date().getTime();
              let curTime = utilJs.dateFormat(nowTimeTamp);
                //日历打卡,若当前日期不在开始日期和结束日期之间，则从开始日期进入，否则从当前日期进入
              if (nowTimeTamp < startTimeTamp || nowTimeTamp > endTimeTamp) {
                curTime = this.clockInInfo.startTime;
              }
              this.wxappQuery = `workType=1&fromDetail=1&cId=${localStorage.getItem("companyId")}&clockInId=${this.clockInInfo.signColId}&curSelectDate=${curTime}`
              break;
            case 2:
              this.wxappQuery = `workType=2&fromDetail=1&cId=${localStorage.getItem("companyId")}&clockInId=${this.clockInInfo.signColId}&curId=${this.clockInInfo.hwId}`
              //作业打卡，如果超过一个作业，则进入作业列表，否则进入作业详情
              break;
            case 3:
              this.wxappQuery = `workType=3&fromDetail=1&cId=${localStorage.getItem("companyId")}&clockInId=${this.clockInInfo.signColId}&curId=${this.clockInInfo.hwId}`
              //闯关打卡
              break;
          }
      }
    }
  },
  methods: {
  clickGoWxApp() {
      let fullPath = `${this.path}?${this.wxappQuery}`;
      let query = `?appId=${this.appid}&path=${encodeURIComponent(JSON.stringify(fullPath))}`;
      utilJs.miniProgramGoTo('push', '/pages/home/goWxApp/index' + query);
    },
    handleLaunch(e) {
        console.log('handleLaunch---', e)
        // this.$emit('handleLaunch')
    },
    handleErrorFn(e) {
      this.$showCjToast({
        text: e.errMsg || '无法打开小程序，请升级微信版本',
        type: "warn",
        time: 1500
      })
    },
    closeAudioRecordModal() {
      this.mediaIds = []
      this.localMedId = []
      this.showRecordTime = 0
      this.recordTime = 0;
      clearInterval(recordTimeCon);
      this.$emit("closeAudioRecordModal", 1);
    },
    //录音相关
    clickStartRecord(e) {
      if (this.recordStatus == "START") {
        this.startVioceRecord();
      }
    },
    voiceAutoSend() {
      this.clickSentRecord();
    },
    //点击开始录音
    startVioceRecord() {
      //点击开始录音
      this.stopListenAudio();
      this.recordStatus = "RECORDING";
      this.recordTime = 0;
      if (this.isWeiXin && !this.isPcWechat) {
        wxUtilJs.startRecord().then(res => {
            recordTimeCon = setInterval(() => {
              if (this.recordTime < 60) {
                this.recordTime++;
                this.showRecordTime++
              } else {
                clearInterval(recordTimeCon);
                if (!this.enableLongAudio) {
                  this.recordStatus = "END";
                }
              }
            }, 1000);
          }, failRes => {
          this.$showCjToast({
            text: "开启录音失败",
            type: "warn",
            time: 1000
          });
          this.recordStatus = "START";
        });
        wxUtilJs.onVoiceRecordEnd().then((localId) => {
            if (!this.enableLongAudio) {
              this.recordStatus = "END";
            }
            this.$loading.hide();
            clearInterval(recordTimeCon);
            currentLocalId = localId;
            console.log(currentLocalId, 'onVoiceRecordEnd')
            this.voiceAutoSend();
        });
        return;
      }
      record.recOpen(() => {
          record.recStart();
          recordTimeCon = setInterval(() => {
            if (this.recordTime < 60) {
              this.recordTime++;
              this.showRecordTime++
            } else {
              clearInterval(recordTimeCon);
              if (!this.enableLongAudio) {
                this.recordStatus = "END";
              }
              record.recStop((res) => {
                this.blob = res;
                this.voiceAutoSend(res);
              });
            }
          }, 1000);
        }, () => {
          this.recordStatus = "START";
      });
    },

    //点击停止录音
    clickStopRecord() {
      if (this.recordStatus != "RECORDING") {
        return;
      }
      this.recordStatus = "END";
      clearInterval(recordTimeCon);
      if (this.isWeiXin && !this.isPcWechat) {
        wxUtilJs.stopRecord().then((localId) => {
          currentLocalId = localId;
          this.clickSentRecord(1)
        });
      } else {
        record.recStop((res) => {
          this.blob = res;
          this.clickSentRecord(1)
        });
      }
      if (this.recordTime < 1) {
        this.$showCjToast({
          text: "录音时间太短",
          type: "warn",
          time: 1000
        });
        this.recordStatus = "START";
        return
      }
    },

    //点击重录
    clickRecordAgain() {
      this.recordStatus = "START";
      this.mediaIds = [];
      this.localMedId = [];
      this.showRecordTime = 0
      this.recordTime = 0;
      clearInterval(recordTimeCon);
    },
    //点击试听
    clickTryListen(start) {
      if (!this.isWeiXin) {
        return;
      }
      let that = this
      if (start == 1) {
        that.mediaIndex = 0
      }
      console.log(that.localMedId, that.mediaIndex, that.localMedId[that.mediaIndex])
      if (that.localMedId.length != 0) {
        that.isPlayTest = true;
        wxUtilJs.playVoice({
          localId: that.localMedId[that.mediaIndex]
        });
      }
      wxUtilJs.onVoicePlayEnd(() => {
        //监听微信语音播放结束事件
        console.log(that.mediaIndex, that.localMedId.length - 1)
        if (that.mediaIndex == that.localMedId.length - 1) {
          that.isPlayTest = false;
          that.mediaIndex = 0
        } else {
          that.mediaIndex++
          that.clickTryListen()
        }
      });
    },
    clickSentRecord(state) {
      if (this.isWeiXin && !this.isPcWechat) {
        console.log(currentLocalId, 'currentLocalId')
        if (currentLocalId) {
          wxUtilJs
            .uploadVoice({
              localId: currentLocalId
              },
              true
            )
            .then((serverId) => {
              this.localMedId.push(currentLocalId)
              this.mediaIds.push(serverId)
              console.log(this.mediaIds, state)
              if (state == 1) {
                return
              }
              if (this.enableLongAudio) {
                this.startVioceRecord();
              } else {
                this.syncUploadAudio()
              }
            });
        } else {
          this.$showCjToast({
            text: "上传失败，请重新录制",
            type: "warn",
            time: 1500
          });
        }
      } else {
        if (this.blob) {
          record.uploadAudioFile(
            this.blob,
            this.qiniuInfo,
            (sres) => {
              this.mediaIds.push(sres)
              if (state == 1) {
                return
              }
              if (this.enableLongAudio) {
                this.startVioceRecord();
              } else {
                this.syncUploadAudio()
              }
              // this.syncUploadAudio(sres, state)
            },
            () => {
              this.$showCjToast({
                text: "上传失败，请重新录制",
                type: "warn",
                time: 1500
              });
            }
          );
        }
      }
    },

    //点击发送
    syncUploadAudio(state) {
      if (this.mediaIds.length == 0) {
        return
      }
      this.$loading.show({
        text: "上传中..."
      });
      this.recordStatus = "START";
      this.stopListenAudio();
      clearInterval(recordTimeCon);
      utilJs.postMethod(
        global.apiurl + "signCard/batchDownWxMediaSpx",
        {
          mediaIds: this.mediaIds
        },
        (res) => {
          this.$loading.hide();
          let audioContent = {
            content: res.audioUrl,
            time: this.showRecordTime
          };
          this.mediaIds = []
          this.localMedId = []
          this.showRecordTime = 0
          this.$emit("uploadAudioSuccess", audioContent);
          this.closeAudioRecordModal()
        },
        (failRes) => {
          this.$loading.hide();
        }
      );
      // utilJs.postMethod(
      //   global.apiurl + "signCard/downWxMediaSpx",
      //   {
      //     content: serverId
      //   },
      //   (res) => {
      //     this.$loading.hide();
      //     let audioContent = {
      //       content: res.audioUrl,
      //       time: this.recordTime
      //     };
      //     this.$emit("uploadAudioSuccess", audioContent);
      //     if (this.enableLongAudio && state != 1) {
      //       this.startVioceRecord();
      //     }
      //   },
      //   (failRes) => {
      //     this.$loading.hide();
      //   }
      // );
    },

    //停止试听
    stopListenAudio() {
      if (this.isPlayTest) {
        wxUtilJs.stopVoice({
          localId: currentLocalId
        });
        this.isPlayTest = false;
        this.mediaIndex = 0
      }
    }
  },
  beforeDestroy() {
    if (!this.isWeiXin && record != null) {
      record.recClose();
    }
    this.mediaIndex = 0
    this.stopListenAudio()
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.modal {
  position: fixed;
  top: 0;
  left: 0;
  z-index: 2020;
  width: 100%;
  height: 100%;
}
.modalSimpleQue{
  position: fixed;
  bottom: 0;
  left: 0;
  z-index: 2020;
  width: 100%;
}
.masker {
  z-index: 888;
  background-color: rgba(0, 0, 0, 0.4);
}
.modal-content {
  position: relative;
  z-index: 999;
}
.c-mt124{
  margin-top: 3.1rem
}
.open-tag-wrap {
  position: absolute;
  z-index: 10;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  background-color: transparent;
}
.launch-btn {
  width: 100%;
  height: 100%;
  display: block;
  overflow: hidden;
}
.open-tag-wrap {
  position: absolute;
  z-index: 10;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  background-color: transparent;
}
</style>
